<script setup lang="tsx">
import type { LoginInfo } from '@/store/modules/user'
import type { FormSchema } from '@fetm/shared-components'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { getAccessToken, getCodeImg, getInfo } from '@/https/api/auth'
import { useUserStore } from '@/store/modules/user'
import { Form, useForm } from '@fetm/shared-components'
import { useValidator } from '@fetm/shared-hooks'
import { ElButton, ElMessage } from 'element-plus'
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const emit = defineEmits(['to-register'])

const { required } = useValidator()

const userStore = useUserStore()

const router = useRouter()

// 验证码开关
const captchaEnabled = ref(true)
const removeCaptcha = computed(() => {
  return !captchaEnabled.value
})
const codeUrl = ref('')
const uuid = ref('')
/**
 * 获取验证码
 */
function getCode() {
  // getCodeImg().then((res) => {
  //   if (res.data) {
  //     captchaEnabled.value
  //       = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
  //     if (captchaEnabled.value) {
  //       codeUrl.value = `data:image/gif;base64,${res.data.img}`
  //       uuid.value = res.data.uuid
  //       console.log(uuid.value)
  //     }
  //   }
  // })
}

getCode()

// 设置表单校验规则
const rules = {
  username: [required()],
  password: [required()],
  code: [required()],
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="w-[100%] text-center text-20px font-bold">登录</h2>
        },
      },
    },
  },
  {
    field: 'username',
    label: '用户名',
    value: '',
    component: 'Input',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'password',
    label: '密码',
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        width: '100%',
      },
    },
  },
  {
    field: 'code',
    label: '验证码',
    remove: removeCaptcha,
    component: 'Input',
    colProps: {
      span: 24,
    },
    componentProps: {
      class: 'w-full code-deep',
      slots: {
        append: () => {
          return (
            <>
              <div class="h-40px">
                <img
                  src={codeUrl.value}
                  onClick={getCode}
                  class="h-full cursor-pointer"
                />
              </div>
            </>
          )
        },
      },
    },
  },
  {
    field: 'login',
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <ElButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  登录
                </ElButton>
              </div>
            </>
          )
        },
      },
    },
  },
  {
    field: 'other',
    hidden: true,
    component: 'Divider',
    label: '其他登录方式',
    componentProps: {
      contentPosition: 'center',
    },
  },
  {
    field: 'otherIcon',
    hidden: true,
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%] flex justify-between">
                <i class="ant-design:github-filled ant-icon h-30px w-30px cursor-pointer color-#999 hover:color-[var(--el-color-primary)]"></i>
                <i class="ant-icon ant-design:wechat-filled h-30px w-30px cursor-pointer color-#999 hover:color-[var(--el-color-primary)]"></i>
                <i class="ant-icon ant-design:alipay-circle-filled h-30px w-30px cursor-pointer color-#999 hover:color-[var(--el-color-primary)]"></i>
                <i class="ant-icon ant-design:weibo-circle-filled h-30px w-30px cursor-pointer color-#999 hover:color-[var(--el-color-primary)]"></i>
              </div>
            </>
          )
        },
      },
    },
  },
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const loading = ref(false)

const redirect = ref<string>('')

watch(
  () => router.currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query.redirect as string
  },
  {
    immediate: true,
  },
)

// 登录
async function signIn() {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<{
        username: string
        password: string
        code: string
      }>()
      try {
        const res = await getAccessToken({
          ...formData,
          uuid: uuid.value,
        })
        if (res.data.code != 200)
          throw new Error(res.data.msg)

        userStore.setToken(`Bearer ${res.data.data.access_token}`)
        const res2 = await getInfo()
        if (res2.data.code != 200)
          throw new Error(res2.data.msg)
        userStore.setUserInfo(res2.data.user)
        userStore.setLoginInfo(res2.data as LoginInfo)
        router.push('/')
      }
      catch (e) {
        // #region ************************************无后台服务测试代码*********************************************
        // TODO 如果连接上服务请注释这段代码
        userStore.setUserInfo({ username: 'test' })
        router.push('/')
        return
        // #endregion *************************************************************************************
        console.error(e)
        ElMessage.error((e as Error).message)
        // 重新获取验证码
        loading.value = false
        if (captchaEnabled.value)
          getCode()
      }
    }
  })
}
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"
    @keyup.enter="signIn"
  />
</template>

<style lang="less" scoped>
:deep(.code-deep .@{elNamespace}-input-group__append) {
  padding: 0;
}
</style>
